package cn.bankAutoOffice.service.impl;

import cn.bankAutoOffice.bean.entity.Department;
import cn.bankAutoOffice.bean.entity.Employee;
import cn.bankAutoOffice.bean.entity.Menu;
import cn.bankAutoOffice.mapper.MenuMapper;
import cn.bankAutoOffice.service.EmployeeService;
import cn.bankAutoOffice.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 金健伟
 * @DATE 2023/4/11 13:06
 * 功能说明：
 */

@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private EmployeeService employeeService;

    @Resource
    private MenuMapper menuMapper;

    public List<Menu> getMenuByCurrentUser() {
        if (SecurityUtils.getSubject().getPrincipal() == null) {
            return null;
        }
        //获取当前登录用户的用户名
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        //根据用户name字段获取当前用户的角色
        List<Department> departments = employeeService.getDepartment(employee.getDepartmentId());
        //获取当前用户的一级菜单id集合
        List<Menu> menus = new ArrayList<>();
        for (Department item : departments) {
            //根据用户角色id获取一级菜单id
            List<Menu> DepartmentMenus = menuMapper.getMenuByDepartmentId(item.getId());
            menus.addAll(DepartmentMenus);
        }
        //添加二级菜单
        List<Menu> result = handleMenus(menus);
        //添加三级菜单
        // List<Menu> fin_result = handleChildMenus(result);
        return result;
    }

    /**
     * 根据一级菜单获取二级菜单
     *
     * @param menus 一级菜单
     * @return 添加了二级菜单的一级菜单
     */
    public List<Menu> handleMenus(List<Menu> menus) {
        for (Menu item : menus) {
            //获取父节点的id为一级菜单id的二级菜单，然后加入到一级菜单的孩子节点中
            List<Menu> children = menuMapper.findMenuByParentId(item.getId());
            item.setChildren(children);
        }
        return menus;
    }

    /**
     * 根据二级菜单获取三级菜单
     *
     * @param menus 拥有二级菜单的一级菜单
     * @return
     */
    public List<Menu> handleChildMenus(List<Menu> menus) {
        for (Menu item : menus) {
            //再次遍历二级菜单获取到三级菜单
            for (int i = 0; i < item.getChildren().size(); i++) {
                List<Menu> children = menuMapper.findMenuByParentId(item.getChildren().get(i).getId());
                item.getChildren().get(i).setChildren(children);
            }
        }
//        //删除所有父节点不为0的菜单
//        menus.removeIf(item -> item.getParentid() != 0);
        return menus;
    }

}
